package com.quan.system.web.controller;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.ResultBean;
import com.quan.common.core.MyBaseController;
import com.quan.system.common.dto.InitPermissionDTO;
import com.quan.system.entity.SystemPermission;
import com.quan.system.service.SystemPermissionService;

/**
 * <p>
 * 通用用户权限系统-菜单权限表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-05
 */
@RestController
@RequestMapping("/system/permission")
public class SystemPermissionController extends MyBaseController {

	@Autowired 
    private SystemPermissionService service;
    
    /**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody SystemPermission entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		boolean save = this.service.save(entity);
		if (save) {
			return ResultBean.ok("提交成功");
		} else {
			return ResultBean.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 批量删除
	 * 
	 * @param params idList:["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody SystemPermission entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return ResultBean.ok("修改成功");
		} else {
			return ResultBean.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		SystemPermission entity = this.service.getById(id);
		if (null != entity) {
			return ResultBean.ok(entity);
		} else {
			return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(SystemPermission entity) {
		return ResultBean.ok(this.service.list(new QueryWrapper<SystemPermission>(entity)));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(SystemPermission entity) {
		return ResultBean.ok(this.service.selectPage(new QueryWrapper<SystemPermission>(entity).orderByDesc("ctime"), new PageBean(request)));
	}
	
	/**
	 * 根据菜单ID加载对应权限
	 * @param menuId
	 * @return
	 */
	@GetMapping(value = "/findPermissionByMenuId/{menuId}")
	public Object findPermissionByMenuId(@PathVariable Serializable menuId) {
		return ResultBean.ok(this.service.findPermissionByMenuId(menuId));
	}

	/**
	 * 初始化菜单权限（页面，添加，修改，删除，详情，查询）
	 * @param dto
	 * @return
	 */
	@PostMapping("/initPermission")
	public Object initPermission(@RequestBody InitPermissionDTO dto) {
		
		for (String p : dto.getPermissions()) {
			String[] split = p.split("-");
			
			SystemPermission sp = new SystemPermission() ;
			sp.setMenuId(dto.getMenuId());
			sp.setName(split[1]);
			sp.setPermission(split[0]);
			sp.setSort(99);
			sp.setType("2");
			sp.setStatus(true);
			
			this.service.save(sp) ;
		}
		
		
		return ResultBean.ok();
	}
	
}



